package com.ruoyi.quartz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.combat.domain.neo4j.CombatAtlasTask;
import com.ruoyi.combat.domain.neo4j.OrgNode;
import com.ruoyi.combat.repository.CombatAtlasTaskRepository;
import com.ruoyi.combat.repository.ForecastOrgNodeRepository;
import com.ruoyi.combat.repository.IpNodeRepository;
import com.ruoyi.combat.repository.OrgNodeRepository;
import com.ruoyi.combat.service.externalServiceInvoker.AntiIpHomingService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.quartz.service.AntiHomingTaskService;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class AntiHomingTaskServiceImpl implements AntiHomingTaskService {

    @Autowired
    private CombatAtlasTaskRepository combatAtlasTaskRepository;
    @Autowired
    private AntiIpHomingService antiIpHomingService;
    @Autowired
    private ForecastOrgNodeRepository forecastOrgNodeRepository;
    @Autowired
    private OrgNodeRepository orgNodeRepository;
    @Autowired
    private IpNodeRepository ipNodeRepository;
    @Autowired
    private SysConfigMapper sysConfigMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void predictAntiHomingTask() {
        try {
            List<CombatAtlasTask> byTypeCombatAtlasTasks = combatAtlasTaskRepository.findByAtlasTaskPage("2");
            if (CollectionUtil.isNotEmpty(byTypeCombatAtlasTasks)) {
                byTypeCombatAtlasTasks.forEach(combatAtlasTask -> {
                    String targetIp = combatAtlasTask.getTargetIp();
                    List<String> ips = CollectionUtil.newArrayList(targetIp);
                    SysConfig sysConfig = sysConfigMapper.selectConfigById(8L);
                    if ("true".equals(sysConfig.getConfigValue())) {
                        // 进行抗归属状态查询
                        Map<String, Object> stringObjectMap = antiIpHomingService.getPredictRelationshipStatus(ips);
                        String adversarial_status = (String) stringObjectMap.get("adversarial_status");
                        if ("对抗停止".equals(adversarial_status)) {
                            Map<String, Object> map = antiIpHomingService.predictIpHoming(ips);
                            Map<String,Object> analysisResults = (Map<String,Object>)map.get("analysis_results");
                            if (analysisResults != null) {
                                Map<String, Object> result = (Map<String, Object>)analysisResults.get(targetIp);
                                if (result.get("top_organization") instanceof Map) {
                                    System.out.println("result:"+result.get("top_organization"));
                                    Map<String, Object> topOrg = (Map<String, Object>) result.get("top_organization");
                                    if (topOrg.get("org") != null) {
                                        combatAtlasTask.setAfterRiskOrg((String) topOrg.get("org"));
                                    }
                                } else if (result.get("error") != null) {
                                    String error = (String) result.get("error");
                                    combatAtlasTask.setAfterRiskOrg(error);
                                }
                            }
                            combatAtlasTask.setTaskStatus("2");
                            combatAtlasTask.setEndTime(DateUtils.getTime());
                            combatAtlasTaskRepository.updateCombatAtlasTaskById(combatAtlasTask.getId(), combatAtlasTask.getTaskStatus(), combatAtlasTask.getEndTime(), combatAtlasTask.getAfterRiskOrg());

                            // 删除预测的IP-组织关系
                            String beforeRiskOrg = combatAtlasTask.getBeforeRiskOrg();
                            forecastOrgNodeRepository.deleteByNameAndIP(beforeRiskOrg, targetIp);
                        }
                    } else {
                        // 查询所有组织
                        List<OrgNode> allOrg = orgNodeRepository.findOrgNodeByNotName(combatAtlasTask.getBeforeRiskOrg());
                        if (CollectionUtil.isNotEmpty(allOrg)) {
                            OrgNode orgNode = allOrg.get(0);
                            combatAtlasTask.setAfterRiskOrg(orgNode.getName());
                        }
                        combatAtlasTask.setTaskStatus("2");
                        combatAtlasTask.setEndTime(DateUtils.getTime());
                        combatAtlasTaskRepository.updateCombatAtlasTaskById(combatAtlasTask.getId(), combatAtlasTask.getTaskStatus(), combatAtlasTask.getEndTime(), combatAtlasTask.getAfterRiskOrg());
                        // 删除预测的IP-组织关系
                        String beforeRiskOrg = combatAtlasTask.getBeforeRiskOrg();
                        forecastOrgNodeRepository.deleteByNameAndIP(beforeRiskOrg, targetIp);
                    }
                });
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public void getAntiHomingStatus() {
        try {
            List<CombatAtlasTask> byTypeCombatAtlasTasks = combatAtlasTaskRepository.findByAtlasTaskPage("1");
            if (CollectionUtil.isNotEmpty(byTypeCombatAtlasTasks)) {
                byTypeCombatAtlasTasks.forEach(combatAtlasTask -> {
                    SysConfig sysConfig = sysConfigMapper.selectConfigById(8L);
                    String targetIp = combatAtlasTask.getTargetIp();
                    if ("true".equals(sysConfig.getConfigValue())) {
                        // 进行确定风险抗归属状态查询
                        Map<String, Object> stringObjectMap = antiIpHomingService.getAntiIpHomingStatus();
                        if (ObjectUtil.isNotNull(stringObjectMap)) {
                            String status =  (String)stringObjectMap.get("status");
                            if ("success".equals(status)) {
                                // 删除指定IP的BELONG_TO关系
                                ipNodeRepository.deleteRelationsByIpAndBelongsTo(targetIp);
                                combatAtlasTask.setTaskStatus("2");
                                combatAtlasTask.setEndTime(DateUtils.getTime());
                                combatAtlasTaskRepository.updateCombatAtlasTaskById(combatAtlasTask.getId(), combatAtlasTask.getTaskStatus(), combatAtlasTask.getEndTime(), combatAtlasTask.getAfterRiskOrg());
                            } else {
                                log.error("进行确定风险抗归属状态查询失败：" + JSONUtil.toJsonStr(stringObjectMap));
                            }
                        }
                    } else {
                        // 删除指定IP的BELONG_TO关系
                        ipNodeRepository.deleteRelationsByIpAndBelongsTo(targetIp);
                        combatAtlasTask.setTaskStatus("2");
                        combatAtlasTask.setEndTime(DateUtils.getTime());
                        combatAtlasTaskRepository.updateCombatAtlasTaskById(combatAtlasTask.getId(), combatAtlasTask.getTaskStatus(), combatAtlasTask.getEndTime(), combatAtlasTask.getAfterRiskOrg());
                    }

                });
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
